import {Component, OnInit, Input} from '@angular/core';
import {ApiService} from "@core/services/http/api.service";
import {GridConfigService} from 'app/core/config/grid-config.service';
import {GridOptions} from '@ag-grid-community/core';
import {ApesMessageService} from "@shared/apes/message";
import {UserAuthService} from "@core/services/user-auth.service";
import { BiService } from '../../../bi.service';

@Component({
  selector: 'apes-pick-car-proportion',
  templateUrl: './pick-car-proportion.component.html',
  styleUrls: ['../../door-tube-center-all.scss']
})
export class PickCarProportionComponent implements OnInit {
  /* 按钮相关 */
  buttonBar = [
    { hide: true, style: 'default', label: '查询', id: 'action_query',loading: false }
  ];
  title = '';
  ctx = { model: {} };

  /** Grid 相关 **/
  rowData:any[] = [];
  resultData:any;
  gridOptions:GridOptions;
  pinnedBottomRowData:any[] = [];
  columnDefs:any[] = [];
  height:any = window.innerHeight - 200 + 'px';

  hind: string = 'none';
  timeList: any = [];       // 日期
  startValue: Date = null;
  endValue: Date = null;
  endDate = null;                     // 默认结束时间
  startDate = null;                   // 默认开始时间 当天
  days: any;
  saleList:any [];
  sale = [];
  saleID: any[];
  userInfo = this.userAuthService.getUserInfoObj();
  companyId = this.userInfo.userAccount.post.company.id;
  companyData :any;
  companyList: any[];

  constructor(private apiService:ApiService,
              private gridConfigService:GridConfigService,
              private msg: ApesMessageService,
              private userAuthService: UserAuthService,
              private bi: BiService) {
    this.columnDefs = [
      {headerName: "接车人员", field: 'RYMC'},
      {headerName: "所在门店", field: 'MDMC'},
      {headerName: "销售组", field: 'XSZMC'},
      {headerName: "接车总数", field: 'JCZS'},
      {headerName: "门店车流", field: 'MDJCZS'},
      {headerName: "门店车流占比", field: 'JCZB'},
      {headerName: "保养回访量", field: 'GZBY'},
      {headerName: "年审回访量", field: 'GZNS'},
      {headerName: "报案回访量", field: 'GZBA'},
      {headerName: "保险回访量", field: 'GZBX'},
      {headerName: "客诉回访量", field: 'GZKS'},
      {headerName: "二手车回访量", field: 'GZESC'},
      {headerName: "未成交项目回访量", field: 'GZXM'},
      {headerName: "未成交服务单回访量", field: 'GZFWD'},
      {headerName: "意向回访量", field: 'GZYX'},
      {headerName: "大单回访量", field: 'GZBIG'}
    ];

    // 初始化 grid
    this.gridOptions = <GridOptions>{
      toolPanelSuppressSideButtons: true,
      suppressExcelExport: true,
      suppressCsvExport: true,
      showToolPanel: false,
      pagination: true,
      paginationPageSize: 30,
      rowHeight: 35
    };
    this.gridOptions.localeText = gridConfigService.getLocaleText();
    this.companyList = [];
    this.companyList.push(this.companyId);
  }

  ngOnInit() {
    // 默认 请求 当天 数据
    this.endDate = new Date();
    this.startDate = new Date(this.endDate.getTime() - (0 * 24 * 60 * 60 * 1000));
    this.timeList.push(this.startDate);
    this.timeList.push(this.endDate);
    this.queryData();
    this.getSaleData();
    this.bi.getCompany(this.userInfo.userAccount.post.localPermit.id).then(value => { this.companyData = value });
  }

  onEvent(data: any) {

    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_query') {
        this.buttonBar[0].loading = true;
        this.queryData();
      }
    }
  }

  // 日期相减
  getTimeChang(d1, d2) {
    let day = 24 * 60 * 60 * 1000;
    try {
      let dateArr = d1.split('-');
      let checkDate = new Date();
      checkDate.setFullYear(dateArr[0], dateArr[1] - 1, dateArr[2]);
      let checkTime = checkDate.getTime();

      let dateArr2 = d2.split('-');
      let checkDate2 = new Date();
      checkDate2.setFullYear(dateArr2[0], dateArr2[1] - 1, dateArr2[2]);
      let checkTime2 = checkDate2.getTime();
      this.days = (checkTime - checkTime2) / day;
      if (this.days < 1) {
        return 'hide';
      } else {
        return 'show';
      }
    } catch (e) {
      return false;
    }
  }

  // 查询按钮事件
  queryData() {
    // if(this.companyList.length <= 0){
    //   this.companyList.push(this.companyId);
    // }
    this.rowData = [];
    this.getDate(this.timeList, 'startValue', 'endValue');
    if (this.getTimeChang(this.endValue, this.startValue) === 'show') {
      this.hind = 'block';
    } else {
      // 判断日期不能为空
      if (this.startValue === null) {
        this.hind = 'block';
      }else{
        this.hind = 'none';
      }
    }
    //  必须满足以下条件才能调用接口
    if( this.hind === 'none'){
      this.getTablesData();
    }
  }

  // 日期转换
  getDate(time: any[], time_ks: string, time_js: string) {
    // debugger;
    let [first, second] = time;
    if (first) {
      this[time_ks] = first.toISOString().slice(0, 10);
    } else {
      this[time_ks] = null;
    }

    if (second) {
      this[time_js] = second.toISOString().slice(0, 10);
    } else {
      this[time_js] = null;
    }

  }

  // 获取销售组
  getSaleData() {
    let data = {
      'interfaceMethod': 'ipmQueryXszService.queryXszData', 'pdata': { 'MJBJ': 0 },
    };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        // debugger;
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            this.saleList = data;
            this.sale = this.saleList;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  getTablesData() {
    let data = {'interfaceMethod': 'ipmMgzzForAppService.getJcjdJczb', 'pdata': {'XZRQ_SJ': this.startValue, 'XSZID': this.saleID, 'companyId': this.companyList}};
    this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj)
            for (let i = 0, len = data.length; i < len; i++) {
              data[i]['JCZB'] = data[i]['JCZB'] + '%';
            }
            this.rowData = data;
            if( this.rowData.length === 0 ) {
              this.msg.info(`未找到满足条件的数据`);
            }
            this.buttonBar[0].loading = false;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

}

